using Cysharp.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

namespace DTFramework.Util
{
    public class CheckNetEnvirUtil
    {
        private const string INTERNETURL = "http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp";

        private TimeStampSetting setting;

        private float _requestTimeInterval = 3, _initTime = 3;
        private bool _connectInternet = false, _YetDue = true;
        private Dictionary<string, bool> m_LoadedFlag = new Dictionary<string, bool>();
        private bool _isUseTimeStamp = false;
        private DateTime _deadlineTime = DateTime.MinValue, _currentInternetTime = DateTime.MaxValue;

        public event Action<bool, string> OnCheckForm;
        public bool IsCanRunning=false;

        public CheckNetEnvirUtil(TimeStampSetting setting)
        {
            this.setting = setting;
            _isUseTimeStamp=setting.IsUseTimeStamp;
        }
        public async void OnEnter()
        {
            OnCheckForm?.Invoke(false, null);
            _connectInternet = await GetWebNetAsync();
            if (!_connectInternet) CheckInternetEnvir();//检查联网                            
            if (_isUseTimeStamp) CheckNetTimeStamp();  //使用时间戳
        }
        public void OnUpdate()
        {
            //检查联网
            if (!_connectInternet)
            {
                if (Time.realtimeSinceStartup - _initTime > _requestTimeInterval)
                {
                    CheckInternetEnvir();
                    _initTime = Time.realtimeSinceStartup;
                }
            }
            // 使用时间戳
            if (_isUseTimeStamp && _YetDue)
            {
                if (Time.realtimeSinceStartup - _initTime > _requestTimeInterval + 10)
                {
                    CheckNetTimeStamp();
                    _initTime = Time.realtimeSinceStartup;
                }
            }

            foreach (var loadedFlag in m_LoadedFlag)
            {
                if (!loadedFlag.Value)
                {
                    return;
                }
            }
            IsCanRunning=true;
        }

        private async void CheckInternetEnvir()
        {
            if (Application.internetReachability != NetworkReachability.NotReachable)
            {
                m_LoadedFlag["CheckInternetEnvir"] = false;
                var result = await GetWebNetAsync();
                if (!result)
                {
                    OnCheckForm?.Invoke(false, "当前设备无网络环境，请检查网络设备。。。");
                    _connectInternet = false;
                    _initTime = 3;
                }
                else
                {
                    m_LoadedFlag["CheckInternetEnvir"] = true;
                    _connectInternet = true;
                }
            }
        }

        private async void CheckNetTimeStamp()
        {
            m_LoadedFlag["CheckTimeStamp"] = false;

            //请求服务器配置时间
            var deadlineUrl = setting.DEADLINEURL;
            var request = UnityWebRequest.Get(deadlineUrl);
            var result = await request.SendWebRequest();

            if (result.result != UnityWebRequest.Result.ConnectionError)
            {
                _deadlineTime = Convert.ToDateTime(result.downloadHandler.text);
            }
            if (_currentInternetTime < _deadlineTime)
            {
                m_LoadedFlag["CheckTimeStamp"] = true;
                _YetDue = false;
            }
            else
            {
                OnCheckForm?.Invoke(false, "当前设备已过期，请联系管理员。。。");
            }
        }

        //请求网络时间
        private async UniTask<bool> GetWebNetAsync()
        {
            var request = UnityWebRequest.Get(INTERNETURL);
            var result = await request.SendWebRequest();

            if (result.result != UnityWebRequest.Result.ConnectionError)
            {
                try
                {
                    var jObject = JObject.Parse(result.downloadHandler.text);
                    long timestamp = long.Parse(jObject["data"]["t"].ToString());
                    DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                    _currentInternetTime = dateTime.AddMilliseconds(timestamp).ToLocalTime();
                    return true;
                }
                catch { }
            }
            return false;
        }
    }
}
